package com.starmark.gateway.pt.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.starmark.core.framework.base.AbstractBaseService;
import com.starmark.gateway.pt.provider.entity.PtDataSource;
import com.starmark.gateway.pt.provider.mapper.PtDataSourceMapper;
import com.starmark.gateway.pt.provider.service.IPtDataSourceService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.SneakyThrows;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.Map;

/**
 * <p>
 * 数据源 服务实现类
 * </p>
 *
 * @author starmark
 * @since 2020-05-24
 */
@Service
public class PtDataSourceServiceImpl extends AbstractBaseService<PtDataSourceMapper, PtDataSource> implements IPtDataSourceService {


    @Override
    public void buildPageSearch(Map<String, Object> params, QueryWrapper<PtDataSource> eWrapper) {
        if (params.get("keyword") != null && StrUtil.isNotEmpty(params.get("keyword") + "")) {
            eWrapper.like("name", params.get("keyword") + "");
        }
        //查询工程ID
        eWrapper.eq("project_code", params.get("projectCode") + "");

    }

    @SneakyThrows
    @Override
    public boolean test(PtDataSource ptDataSource) {
        DataSource dataSource=this.buildDataSource(ptDataSource);
          return dataSource.getConnection()==null;
    }

    private DataSource buildDataSource(PtDataSource ptDataSource){
        HikariConfig hikariConfig=new HikariConfig();
        hikariConfig.setJdbcUrl(ptDataSource.getJdbcUrl());
        hikariConfig.setUsername(ptDataSource.getUserName());
        hikariConfig.setPassword(ptDataSource.getDataPassword());
        hikariConfig.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        hikariConfig.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        hikariConfig.addDataSourceProperty("useLocalSessionState", "true");
        hikariConfig.addDataSourceProperty("useLocalTransactionState", "true");
        hikariConfig.addDataSourceProperty("rewriteBatchedStatements", "true");
        hikariConfig.addDataSourceProperty("cacheResultSetMetadata", "true");
        hikariConfig.addDataSourceProperty("cacheServerConfiguration", "true");
        hikariConfig.addDataSourceProperty("elideSetAutoCommits", "true");
        hikariConfig.addDataSourceProperty("maintainTimeStats", "false");
        return new HikariDataSource(hikariConfig);
    }
}
